# Importing Data
NEITHERLAND <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Lebanon/Neitherland.xlsx")

# Checking the Imported Data
View(NEITHERLAND)

# Creating Time Series Data
NEITHERLAND_ts <- ts(NEITHERLAND, start=c(2004,03), end=c(2019,06), frequency=12)

# Viewing and Checking the Created Time Series Data
NEITHERLAND_ts
sum(is.na(NEITHERLAND_ts))
library(forecast)
NEITHERLAND_ts <- tsclean(NEITHERLAND_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(NEITHERLAND_ts)
plot(aggregate(NEITHERLAND_ts,FUN=mean))

# Decomposing
NEITHERLAND_ts_decomp <- decompose(NEITHERLAND_ts)
plot(NEITHERLAND_ts_decomp)

# Testing for Stationarity
acf(NEITHERLAND_ts, lag.max=20)
pacf(NEITHERLAND_ts, lag.max=20)

# To see any seasonal effect
boxplot(NEITHERLAND_ts~cycle(NEITHERLAND_ts))

# To remove trend effect
NEITHERLAND_ts_diff <- diff(NEITHERLAND_ts)
plot(NEITHERLAND_ts_diff)

# To remove variance effect
NEITHERLAND_ts_log <- log(NEITHERLAND_ts)
plot(NEITHERLAND_ts_log)

# To remove both (Trend and Variance) effects
NEITHERLAND_ts_both <- diff(log(NEITHERLAND_ts))
plot(NEITHERLAND_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(NEITHERLAND_ts, lag.max=20)
acf(log(NEITHERLAND_ts), lag.max=20)
acf(diff(NEITHERLAND_ts), lag.max=20)
acf(diff(log(NEITHERLAND_ts)), lag.max=20)
pacf(NEITHERLAND_ts, lag.max=20)
pacf(log(NEITHERLAND_ts), lag.max=20)
pacf(diff(NEITHERLAND_ts), lag.max=20)
pacf(diff(log(NEITHERLAND_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
NEITHERLAND_ts_model <- auto.arima(NEITHERLAND_ts)
NEITHERLAND_ts_model
NEITHERLAND_ts_model <- auto.arima(NEITHERLAND_ts, ic="aic", trace = TRUE)
NEITHERLAND_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(NEITHERLAND_ts_model$resid)
acf(NEITHERLAND_ts_model$residuals, main='ACF Residual')
pacf(NEITHERLAND_ts_model$residuals, main='ACF Residual')
Box.test(NEITHERLAND_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
NEITHERLAND_ts_forecast <- forecast (NEITHERLAND_ts_model, level=c(95), h=258)
plot(NEITHERLAND_ts_forecast)
NEITHERLAND_ts_forecast             


write.table(NEITHERLAND_ts_forecast, file="Neitherland_TSA.csv", sep=",")
